/*
    Copyright (c) 2020 Shanghai Macrogiga Electronics Co., Ltd.

    Permission is hereby granted, free of charge, to any person 
    obtaining a copy of this software and associated documentation 
    files (the "Software"), to deal in the Software without 
    restriction, including without limitation the rights to use, copy, 
    modify, merge, publish, distribute, sublicense, and/or sell copies 
    of the Software, and to permit persons to whom the Software is 
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be 
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
    DEALINGS IN THE SOFTWARE.
*/
#include "BSP.h"
#include "mg_api.h"



WWDG_HandleTypeDef wwdg_test = {0};
UART_HandleTypeDef sUartxHandle = {0};

void GPIO_Init(void)
{
    GPIO_InitTypeDef gpioinitstruct={0};

    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    
    gpioinitstruct.Pin  = LED_PIN ;
    gpioinitstruct.Mode = GPIO_MODE_OUTPUT;
    gpioinitstruct.OpenDrain = GPIO_PUSHPULL;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_LOW;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_LOW;
    gpioinitstruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(LED_GPIO, &gpioinitstruct);
    
    gpioinitstruct.Pin = IRQ_PIN;
    gpioinitstruct.Pull = GPIO_PULLUP;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_HIGH;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_HIGH;
    /* Configure Button pin as input */
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(IRQ_GPIO, &gpioinitstruct);

    /* Configure Button pin as input with External interrupt */
    gpioinitstruct.Mode   = EXTI_MODE;
    gpioinitstruct.Exti.Enable = GPIO_EXTI_INT_ENABLE;
    gpioinitstruct.Exti.EdgeLevelSel = GPIO_EXTI_INT_EDGE;
    gpioinitstruct.Exti.RiseFallSel = GPIO_EXTI_INT_LOWFALL;
    HAL_GPIO_Init(IRQ_GPIO, &gpioinitstruct);

    __HAL_GPIO_EXTI_CLEAR_FLAG(IRQ_GPIO, IRQ_PIN);
    /* Enable and set Button EXTI Interrupt to the lowest priority */
    HAL_NVIC_SetPriority(GPIOB_IRQn, PRIORITY_LOW);
    HAL_NVIC_EnableIRQ(GPIOB_IRQn);
    
    gpioinitstruct.Pin = BUT_PIN;
    gpioinitstruct.Pull = GPIO_PULLDOWN;
    gpioinitstruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    gpioinitstruct.SlewRate = GPIO_SLEW_RATE_HIGH;
    gpioinitstruct.DrvStrength = GPIO_DRV_STRENGTH_HIGH;
    /* Configure Button pin as input */
    gpioinitstruct.Mode   = GPIO_MODE_INPUT;
    HAL_GPIO_Init(BUT_GPIO, &gpioinitstruct);
    
    /* Configure Button pin as input with External interrupt */
    gpioinitstruct.Mode   = EXTI_MODE;
    gpioinitstruct.Exti.Enable = GPIO_EXTI_INT_ENABLE;
    gpioinitstruct.Exti.EdgeLevelSel = GPIO_EXTI_INT_EDGE;
    gpioinitstruct.Exti.RiseFallSel = GPIO_EXTI_INT_LOWFALL;
    HAL_GPIO_Init(BUT_GPIO, &gpioinitstruct);

    __HAL_GPIO_EXTI_CLEAR_FLAG(BUT_GPIO, BUT_PIN);
    /* Enable and set Button EXTI Interrupt to the lowest priority */
    HAL_NVIC_SetPriority(GPIOC_IRQn, PRIORITY_LOW);
    HAL_NVIC_EnableIRQ(GPIOC_IRQn);

}

void SystemClock_Config(void) //24M
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};	
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HIRC;
    RCC_OscInitStruct.HIRCState = RCC_HIRC_ON;
    RCC_OscInitStruct.HIRCCalibrationValue = RCC_HIRCCALIBRATION_24M;
    
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    
    /**Initializes the CPU, AHB and APB busses clocks 
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HIRC;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APBCLKDivider = RCC_PCLK_DIV1;
    
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
}

static void SystemClock_4M(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};	
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HIRC;
    RCC_OscInitStruct.HIRCState = RCC_HIRC_ON;
    RCC_OscInitStruct.HIRCCalibrationValue = RCC_HIRCCALIBRATION_4M;
    
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    
    /**Initializes the CPU, AHB and APB busses clocks 
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HIRC;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APBCLKDivider = RCC_PCLK_DIV1;
    
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
}

void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    __HAL_RCC_UARTx_GPIO_CLK_ENABLE();
    /**if UARTx
    UART0    GPIO Configuration:    
    PA1     ------> UART0_RXD
    PA2     ------> UART0_TXD
    
    PD3     ------> UART0_RXD
    PD4     ------> UART0_TXD
    */
    GPIO_InitStruct.Pin = UARTx_RX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF;
    GPIO_InitStruct.OpenDrain = GPIO_PUSHPULL;	
    GPIO_InitStruct.Debounce.Enable = GPIO_DEBOUNCE_DISABLE;
    GPIO_InitStruct.SlewRate = GPIO_SLEW_RATE_HIGH;
    GPIO_InitStruct.DrvStrength = GPIO_DRV_STRENGTH_HIGH;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Alternate = UARTx_RX_ALTERNATE_AFn;
    HAL_GPIO_Init(UARTx_RX_PORT, &GPIO_InitStruct);
    
    GPIO_InitStruct.Pin = UARTx_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF;
    GPIO_InitStruct.Alternate = UARTx_TX_ALTERNATE_AFn;
    HAL_GPIO_Init(UARTx_TX_PORT, &GPIO_InitStruct);
}

void Uart_Init(void)
{
    /* Peripheral clock enable */
    __HAL_RCC_UARTx_CLK_ENABLE();
    
    sUartxHandle.Instance = UARTx;
    sUartxHandle.Init.BaudRate = BAUDRATE;
    sUartxHandle.Init.BaudDouble = UART_BAUDDOUBLE_ENABLE;
    sUartxHandle.Init.WordLength = UART_WORDLENGTH_8B;
    sUartxHandle.Init.Parity = UART_PARITY_NONE;
    sUartxHandle.Init.Mode = UART_MODE_TX_RX;
    HAL_UART_Init(&sUartxHandle);
    
    //HAL_UART_Transmit_IT(&sUartxHandle, ucSendData, sizeof(ucSendData));
    //HAL_UART_Receive_IT(&sUartxHandle, ucReceiveData, sizeof(ucReceiveData));	
    UARTx->SCON  |= UART_INTSR_RI | UART_INTSR_TI;
    HAL_NVIC_EnableIRQ(UARTx_IRQn);
}


void BSP_Init(void)
{
    HAL_Init();
    SystemClock_Config();
    SPIM_Init();
    GPIO_Init();
    Uart_Init();
    LPTIM_Init(LIRC_VALUE);
}

void LED_ONOFF(unsigned char onFlag)//module indicator,GPA8
{
    if(onFlag){
        HAL_GPIO_WritePin(LED_GPIO,LED_PIN,GPIO_PIN_RESET);//low, on
    }else{
        HAL_GPIO_WritePin(LED_GPIO,LED_PIN,GPIO_PIN_SET);//high, off
    }
}

u8 system4MFlag = 0;
static void McuDeepSleep(void)
{
    SystemClock_4M();
    system4MFlag = 1;
    
    SCB->SCR |= 0x04;
    __WFI();
}

#define TOUT_STDBY 600 //1000/200*60*2 = 2 min, 600
extern unsigned int StandbyTimeout;
extern LPTIM_HandleTypeDef sLpTimHandle;
void IrqMcuGotoSleepAndWakeup(void)
{
    if(ble_run_interrupt_McuCanSleep())
    {
        if (TOUT_STDBY < StandbyTimeout)
        {
            StandbyTimeout = 0;
            HAL_LPTIM_Base_Stop(&sLpTimHandle);
            radio_standby();
            LED_ONOFF(0);
            //deep sleep
            McuDeepSleep();
        }
    }
}


/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
